package com.hua.yuan.live.fragment;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.hua.yuan.BaseFragment;
import com.hua.yuan.base.Constents;
import com.hua.yuan.base.ITabFragment;
import com.hua.yuan.live.AnchorDetailActivity;
import com.hua.yuan.live.LiveModule;
import com.hua.yuan.live.LiveRoomActivity;
import com.hua.yuan.live.LiveSearchActivity;
import com.hua.yuan.live.R;
import com.hua.yuan.live.adapter.DisplayLiveAdapter;
import com.hua.yuan.live.listener.OnLiveClickListener;
import com.hua.yuan.live.repertory.cloud_data.loader.LiveSearchIndexLoader;
import com.hua.yuan.live.repertory.cloud_data.res.RoomBean;
import java.util.List;

import cm.hua.yuan.common.utils.AppContextManager;
import cm.hua.yuan.common.utils.PreferenceUtils;

/**
 * @author richsjeson
 * 抽离原先的直播列表首页
 */
public class LiveFragment extends BaseFragment implements
        LoaderManager.LoaderCallbacks<List<RoomBean>>,
        ITabFragment,
        OnLiveClickListener,
        View.OnClickListener{

    /**
     * 显示直播列表
     */
    private ListView mDisplayLiveList;

    private DisplayLiveAdapter mAdapter;

    public final static int TASK_ID=1001;

    private final static String TAG=LiveFragment.class.getSimpleName();

    private final int resutltCode=1001;

    private final int searchResutltCode=1002;

    private RelativeLayout videoSearchRl;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_live, null);
        mDisplayLiveList = view.findViewById(R.id.lv_list_live);
        videoSearchRl=view.findViewById(R.id.videoSearchRl);
        this.mAdapter = new DisplayLiveAdapter(getContext(),this);
        mDisplayLiveList.setAdapter(mAdapter);
        videoSearchRl.setOnClickListener(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LiveSearchIndexLoader loader = (LiveSearchIndexLoader) getLoaderManager().initLoader(TASK_ID, null, this);
        loader.requestData("", "");
    }

    @NonNull
    @Override
    public Loader<List<RoomBean>> onCreateLoader(int id, @Nullable Bundle args) {
        return new LiveSearchIndexLoader(getContext());
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //当页面切换时，需要重新刷新数据
        if(isVisibleToUser){
            LiveSearchIndexLoader loader = (LiveSearchIndexLoader) getLoaderManager().initLoader(TASK_ID, null, this);
            loader.requestData("", "");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //当页面切换时，需要重新刷新数据
//        if(getUserVisibleHint()){
            LiveSearchIndexLoader loader = (LiveSearchIndexLoader) getLoaderManager().initLoader(TASK_ID, null, this);
            loader.requestData("", "");
//        }
    }

    @Override
    public void onLoadFinished(@NonNull Loader<List<RoomBean>> loader, List<RoomBean> data) {
        if(data==null){
            return;
        }
        mAdapter.setData(data);
    }

    @Override
    public void onLoaderReset(@NonNull Loader<List<RoomBean>> loader) {

    }

    @Override
    public void gotoLiveRoom(int position) {
        boolean isLogin=checkLogin();
        if(isLogin){
            Intent intent=new Intent();
            intent.setClassName(getActivity(),"com.hua.yuan.ui.LoginActivity");
            if(getActivity().getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null){
                startActivity(intent);
            }
            return;
        }

        RoomBean roomBean= (RoomBean) mAdapter.getData().get(position);
        if(roomBean==null){
            return;
        }
        //如果主播未开播 则无法进入
        if(roomBean.getIsLive()==0){
            Toast.makeText(getActivity().getApplicationContext(),getResources().getString(R.string.enetr_live_room_error_tip),Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent=new Intent();
        intent.setClass(getContext(), LiveRoomActivity.class);
        //直播的房间号
        intent.putExtra(LiveModule.INTENT_ANCHOR_ID,roomBean.getAnchorId());
        intent.putExtra(LiveModule.INTENT_ANCHOR_NICK_NAME,roomBean.getNickName());
        intent.putExtra(LiveModule.INTENT_ANCHOR_ONLINE,roomBean.getViewNum());
        intent.putExtra(LiveModule.INTENT_ANCHOR_ROOM_NO,roomBean.getRoomNo());
        intent.putExtra(LiveModule.INTENT_ANCHOR_IS_LIVE,roomBean.getIsLive());
        intent.putExtra(LiveModule.INTENT_GROUP_ID,roomBean.getGroudId());
        intent.putExtra(LiveModule.INTENT_ANCHOR_RTC_USER_ID,roomBean.getRtcUserId());
        if(getContext().getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null){
            getActivity().startActivityForResult(intent,resutltCode);
        }
    }

    @Override
    public void gotoLiveDetail(int position) {
        boolean isLogin=checkLogin();
        if(isLogin){
            Intent intent=new Intent();
            intent.setClassName(getActivity(),"com.hua.yuan.ui.LoginActivity");
            if(getActivity().getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null){
                startActivity(intent);
            }
            return;
        }
        RoomBean roomBean= (RoomBean) mAdapter.getData().get(position);
        if(roomBean==null){
            return;
        }

        Intent intent=new Intent();
        intent.setClass(getContext(), AnchorDetailActivity.class);
        //直播的房间号
        intent.putExtra(LiveModule.INTENT_ANCHOR_ID,roomBean.getAnchorId());
        if(getContext().getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null){
            getActivity().startActivityForResult(intent,resutltCode);
        }
    }

    @Override
    public void onClick(View v) {

        if(R.id.videoSearchRl==v.getId()){

            Intent intent=new Intent();
            intent.setClass(getContext(), LiveSearchActivity.class);

            if(getContext().getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null){
                getActivity().startActivityForResult(intent,searchResutltCode);
            }
        }
    }

    private boolean  checkLogin(){
        String token= PreferenceUtils.getString(Constents.TOKEN);
        return TextUtils.isEmpty(token);
    }

    @Override
    public String getTabName() {
       return AppContextManager.getInstance().getContext().getString(R.string.live);
    }

    @Override
    public int getDrawableId() {
        return R.mipmap.main_live_unselect;
    }

    @Override
    public int getDrawableSelectId() {
        return R.mipmap.main_live_select;
    }

    @Override
    public Fragment getTabFragment() {
        return this;
    }
}
